package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Article;
import com.itheima.ydd.entity.Cate;
import com.itheima.ydd.service.ArticleService;
import com.itheima.ydd.service.CateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/ydd_article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CateService cateService;


    @GetMapping("/list")
    public ResultData list(String start_time, String end_time, String title, String cateid, int page, int limit) {
        //分页构造器
        IPage<Article> pageInfo = new Page<>(page, limit);
        //条件构造器
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.between(StringUtils.isNotEmpty(start_time) && StringUtils.isNotEmpty(end_time)
                , Article::getCreate_date, start_time, end_time);

        queryWrapper.like(StringUtils.isNotEmpty(title), Article::getTitle, title)
                .eq(StringUtils.isNotEmpty(cateid), Article::getCateid, cateid);
        //添加排序字段
        queryWrapper.orderByAsc(Article::getId);

        articleService.page(pageInfo, queryWrapper);


        pageInfo.getRecords().stream().map((item) -> {
            Integer cateid1 = item.getCateid();
            Cate byId = cateService.getById(cateid1);
          //  item.setCatename(byId.getCatename());
          if (byId!=null){
              item.setCatename(byId.getCatename());
          }
            return item;
        }).collect(Collectors.toList());

        return ResultData.ok(" ", PageResult.init(pageInfo.getTotal(), pageInfo.getSize(), pageInfo.getPages(), pageInfo.getRecords()));
    }


    @GetMapping("/del")
    public ResultData del(@RequestParam int id) {

        return ResultData.ok(" ", articleService.removeById(id));
    }


    @PostMapping("/add")
    public ResultData add(@RequestBody Article article) {

        return ResultData.ok(" ", articleService.save(article));
    }

    @GetMapping("/rowInfo")
    public ResultData rowInfo(@RequestParam int id) {

        return ResultData.ok(" ", articleService.getById(id));
    }

}
